import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './models/user.entity';
import { DeepPartial, Repository } from 'typeorm';
import { Result } from '@/common/dto/result.type';
import { SUCCESS, UPDATE_ERROR } from '@/common/constants/code';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private UserRepository: Repository<User>,
  ) {}

  async create(entity: DeepPartial<User>): Promise<boolean> {
    const res = await this.UserRepository.insert(entity);
    if (res && res.raw.affectedRows > 0) {
      return true;
    } else {
      return false;
    }
  }
  async del(id: string): Promise<boolean> {
    const res = await this.UserRepository.delete(id);
    if (res.affected > 0) {
      return true;
    } else {
      return false;
    }
  }

  async update(id: string, entity: DeepPartial<User>): Promise<Result> {
    const res = await this.UserRepository.update(id, entity);
    if (res.affected > 0) {
      return {
        code: SUCCESS,
        message: '更新成功',
      };
    } else {
      return {
        code: UPDATE_ERROR,
        message: '更新失败',
      };
    }
  }

  async find(id: string): Promise<User> {
    return await this.UserRepository.findOne({ where: { id } });
  }

  // 通过手机号查询用户
  async findByTel(tel: string): Promise<User> {
    return await this.UserRepository.findOne({ where: { tel } });
  }
  // 更新一个用户的验证码
  async updateCode(id: string, code: string): Promise<boolean> {
    const res = await this.UserRepository.update(id, {
      code,
      codeCreateTimeAt: new Date(),
    });
    if (res.affected > 0) {
      return true;
    } else {
      return false;
    }
  }
}
